package cn.xf.redis.utils;

import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

	@Autowired
	@Getter
	private RedisTemplate<String, Object> totalRedisTemplate;

	/**
	 * 存放string类型
	 * 
	 * @param key
	 *            key
	 * @param data
	 *            数据
	 * @param timeout
	 *            超时间(秒)
	 */
	public void set(String key, Object data, Long timeout) {
		set(key, data, timeout, TimeUnit.SECONDS);
	}

	public void set(String key, Object data, Long timeout, TimeUnit unit) {

		totalRedisTemplate.opsForValue().set(key, data);
		if (timeout != null) {
			totalRedisTemplate.expire(key, timeout, unit != null ? unit : TimeUnit.SECONDS);
		}
	}

	/**
	 * 存放string类型
	 * 
	 * @param key
	 *            key
	 * @param data
	 *            数据
	 */
	public void set(String key, String data) {
		set(key, data, null);
	}

	/**
	 * 根据key查询string类型
	 * 
	 * @param key
	 * @return
	 */
	public Object get(String key) {
		Object value = totalRedisTemplate.opsForValue().get(key);
		return value;
	}

	/**
	 * 根据对应的key删除key
	 * 
	 * @param key
	 */
	public void delKey(String key) {
		totalRedisTemplate.delete(key);
	}

	public Boolean setNx(String key, String value, Long timeout) {
		Boolean absent = totalRedisTemplate.opsForValue().setIfAbsent(key, value);
		if (timeout != null) {
			totalRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
		}
		return absent;
	}

    public void setList(String key, List<String> listToken) {
		totalRedisTemplate.opsForList().leftPushAll(key, listToken);
    }
}
